package com.project.util;

import com.project.server.Servlet;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class AnnotationServletFactory {
    private static Map<String, Servlet> servletMap = new HashMap<>();
    static {
        File file = new File("D:\\java\\JAVA-Two\\chapter2\\lisserver\\src\\main\\java\\com\\project\\service");
        //得到指定目录中所有的文件集合
        File[] fileList = file.listFiles();

        for (File f:fileList) {
            //判断文件对象是否为文件，并且以。java结尾
            if (f.isFile() && f.getName().endsWith(".java")){
                //去掉.java后缀
                String fileName = f.getName().substring(0,f.getName().length()-5);
                //构建业务组件的全路径
                String classPath ="com.project.service."+fileName;
                try {
                    //加载类，得到类模板
                    Class c = Class.forName(classPath);
                    if (c.isAnnotationPresent(WebServlet.class)){//判断类中是否有WebServlet注解
                        //去除WebServlet注解
                        WebServlet webServlet =(WebServlet) c.getAnnotation((WebServlet.class));
                        String url = webServlet.value();
                        servletMap.put(url,(Servlet)c.getConstructor().newInstance());
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    public static Servlet getServlet(String url){
        return servletMap.get(url);
    }

    public static void main(String[] args) {
//        AnnotationServletFactory a = new AnnotationServletFactory();
        System.out.println(servletMap);
    }
}
